#include "../../source/server.hpp"

static std::string UrlEncode(const std::string url, bool convert_space_to_plus)
{
    std::string res;
    for (auto &e : url)
    {
        if (e == '.' || e == '_' || e == '~' || isalnum(e))
        {
            res += e;
            continue;
        }
        if (e == ' ' && convert_space_to_plus == true)
        {
            res += '+';
            continue;
        }
        // 剩下的字符按照%HH格式编译
        char tmp[4] = {0};
        snprintf(tmp, 4, "%%%02X", e);
        res += tmp;
    }
    return res;
}

char HEXTOI(char c)
{
    if (c >= '0' && c <= '9')
        return c - '0';
    else if (c >= 'a' && c <= 'z')
        return c - 'a' + 10;
    else if (c >= 'A' && c <= 'Z')
        return c - 'A' + 10;
    return -1;
}
// URL解码
// 遇到了%，则把其后的两个字符,转换成数字,第一个字符左移4位(*16),再加上第二个字符
static std::string UrlDecode(const std::string url, bool convert_plus_to_space)
{
    std::string res;
    for (int i = 0; i < url.size(); i++)
    {
        if (url[i] == '+' && convert_plus_to_space == true)
        {
            res += ' ';
            continue;
        }
        if(url[i] == '%' && url[i+2] < url.size())
        {
            char v1 = HEXTOI(url[i + 1]);
            char v2 = HEXTOI(url[i + 2]);
            char v = (v1 << 4) + v2;
            res += v;
            i += 2;
            continue;
        }
        res += url[i];
    }
    return res;
}

int main()
{
    std::string str = "C  ";
    std::string res = UrlEncode(str, true);
    std::string tmp = UrlDecode(res,true);
    std::cout << "[" << res << "]" << std::endl;
    std::cout << "[" << tmp << "]" << std::endl;
    return 0;
}